package com.finger.gulimall.member.interceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import com.finger.common.constant.AuthConstant;
import com.finger.common.vo.MemberVo;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

/**
 * @ClassName LoginInterceptor
 * @Description TODO
 * @Author finger
 * @Date 2022/7/3 22:25
 * @Version 1.0
 */

@Component
public class LoginInterceptor implements HandlerInterceptor {

	public static ThreadLocal<MemberVo> loginMember = new ThreadLocal<>();

	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

		HttpSession session = request.getSession();
		MemberVo memberVo = (MemberVo) session.getAttribute(AuthConstant.LOGIN_MEMBER);
		String uri = request.getRequestURI();
		boolean match = new AntPathMatcher().match("/member/member/login", uri);
		if (match) {
			return true;
		}
		if (memberVo == null) {
			// 登陆失败
			response.sendRedirect("http://auth.gulimall.com/login.html?error=-1");
			return false;
		} else {
			// 登录成功
			loginMember.set(memberVo);
			return true;
		}
	}

	@Override
	public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

	}

	@Override
	public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
		loginMember.remove();
	}
}
